package com.lw.sbdemo2.common.base;

import com.alibaba.druid.sql.SQLUtils;
import com.lw.sbdemo2.common.exception.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * <p>标题: 页面书写SQL执行语句</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2017</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: my36z
 * @date 2017/10/25
 */
@Service
public class CommonService extends BaseService {

    @Autowired
    private CommonMapper commonMapper;

    @Value("${sql.maxRow:1000}")
    private String maxRow;

    static String reg = "(?:--)"
            + "(\\b(insert|delete|update|create|drop|truncate|alter|grant|execute|exec|xp_cmdshell|call|declare|source)\\b)";

    static Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);

    public List<Map<String, Object>> findAll(String sql) throws Exception {
        if (sqlPattern.matcher(sql).find()) {
            throw new ApiException("SQL_ERROR");
        }

        String newSql = SQLUtils.addCondition(sql, "rownum < " + maxRow, null);

        return commonMapper.findAll(newSql);
    }
}
